package services

import (
	"main_service/config"
	"main_service/models"
	"sync"
	"time"
)

type CacheService struct {
	stockCache []models.StockBasic
	mu         sync.RWMutex
}

var cacheService *CacheService

func NewCacheService() *CacheService {
	if cacheService == nil {
		cacheService = &CacheService{}
		// 初始化时加载一次数据
		cacheService.loadStockData()
		// 启动定时任务
		go cacheService.startScheduler()
	}
	return cacheService
}

func (s *CacheService) loadStockData() {
	var stocks []models.StockBasic
	result := config.DB.Model(&models.StockBasic{}).Find(&stocks)
	if result.Error != nil {
		return
	}

	s.mu.Lock()
	s.stockCache = stocks
	s.mu.Unlock()
}

func (s *CacheService) startScheduler() {
	// 设置定时器，每天早上8点更新数据
	for {
		now := time.Now()
		next := time.Date(now.Year(), now.Month(), now.Day(), 8, 0, 0, 0, now.Location())
		if now.After(next) {
			next = next.Add(24 * time.Hour)
		}
		time.Sleep(next.Sub(now))
		s.loadStockData()
	}
}

func (s *CacheService) GetStockList() []models.StockBasic {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.stockCache
}
